package com.hks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hks.common.utils.ResponseResult;
import com.hks.mapper.MenuMapper;
import com.hks.pojo.LoginUser;
import com.hks.pojo.Menu;
import com.hks.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    //根节点常量
    private final static Integer TREE_ROOT_CODE = 0;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getMenuListByUserId(Integer userId) {
        //获取当前登录对象的对应菜单列表
        return menuMapper.getMenuListByUserId(userId);
    }

    @Override
    public List<Menu> getMenuTree() {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        List<Menu> menus = menuMapper.selectList(wrapper);
        List<Menu> menuTree = buildTree(menus);
        return menuTree;
    }

    private List<Menu> buildTree(List<Menu> list){

       //1、确定父级节点
        List<Menu> parentList = list.stream().filter(menu -> menu.getParentId() == TREE_ROOT_CODE).collect(Collectors.toList());

        //遍历父级节点
        for (Menu menu : parentList) {
            menu = recursiveTree(menu, list);
        }
        return parentList;
    }

    /**
     * 递归获取子节点
     * @param parent
     * @param list
     * @return
     */
    private Menu recursiveTree(Menu parent,List<Menu> list){
        //子节点的临时list
        List<Menu> childs = new ArrayList<>();
        //1、拿到子节点
        for (Menu menu : list) {
            if (Objects.equals(parent.getId(), menu.getParentId())){
                //再去遍历，查看当前子节点下是否还有其他子节点，递归调用
                menu = recursiveTree(menu,list);
                //将当前的子节点放入临时list
                childs.add(menu);
            }
        }
        parent.setChildren(childs);
        return parent;
    }

}
